package com.ae.shield.common.effect;

import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import net.minecraft.potion.Effect;
import net.minecraft.potion.EffectInstance;
import net.minecraft.util.JSONUtils;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.registries.ForgeRegistries;

import javax.annotation.Nullable;

public class EffectHelper {
    /**
     * json格式：
     *     "effect": "minecraft:speed",
     *     "level": 1,  （可省略，默认为1）
     *     "tick": 6000     (可省略，默认为20)
     * @param json 从json中读取效果
     * @return  返回json中的效果，若未获取则返回null，包含效果等级、效果持续时间
     */
    @Nullable
    public static EffectInstance deserializeEffect(JsonObject json) {
        if (!JSONUtils.hasField(json, "effect")){
            return null;
        }

        String e = JSONUtils.getString(json, "effect");
        Effect effect = ForgeRegistries.POTIONS.getValue(new ResourceLocation(e));

        if (effect == null) {
            throw new JsonSyntaxException("未知的效果 '" + e + "'");
        }

        int level = JSONUtils.getInt(json, "lvl", 1) - 1;
        int tick = JSONUtils.getInt(json, "tick", 20);
        return new EffectInstance(effect, tick, level, true, false);
    }
}
